import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from "@/api/user";
import type { loginForm } from "@/api/user/type";
import type { UserState } from "./types/type.ts";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token.js";
import { constantRoute } from "@/router/routes.js";

const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      avatar: "",
      username: ""
    };
  },
  actions: {
    async userLogin(data: loginForm): Promise<string | Error> {
      let result = await reqLogin(data);
      if (result.code === 200) {
        this.token = result.data.token as string;
        SET_TOKEN(result.data.token as string);
        return "ok";
      } else {
        return Promise.reject(new Error(result.data.message));
      }
    },
    async userInfo() {
      const res = await reqUserInfo();
      if (res.code === 200) {
        this.avatar = res.data.checkUser.avatar;
        this.username = res.data.checkUser.username;
        return "ok";
      }
      return Promise.reject(new Error(res.data.message));
    },
    async userLogout() {
      this.token = "";
      this.username = "";
      this.avatar = "";
      REMOVE_TOKEN();
    }
  },
  getters: {}
});
export default useUserStore;
